package com.syh.askservice.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.syh.askservice.service.FlaskService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.concurrent.CompletableFuture;

/**
 * @author syh 86187
 * @date 2024/7/10
 * com.syh.bishe.service.impl
 * @description
 */
@Service
@Slf4j
@RequiredArgsConstructor
@EnableAsync // 启用异步处理
public class FlaskServiceImpl implements FlaskService {
    private final RestTemplate restTemplate;

    @Override
    public String ask(String question, Integer id, Integer userid) {
        // 构建请求体
        LinkedHashMap<String, Object> requestBody = new LinkedHashMap<>();
        requestBody.put("question", question);
        requestBody.put("company_id", id);
        requestBody.put("user_id", userid);

        ObjectMapper objectMapper = new ObjectMapper();
        String requestBodyJson = "";
        try {
            requestBodyJson = objectMapper.writeValueAsString(requestBody);
        } catch (IOException e) {
            log.error("Error while serializing request body: " + e.getMessage());
            return "请求体序列化失败";
        }

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 创建HttpEntity，包含请求体和请求头
        HttpEntity<String> requestEntity = new HttpEntity<>(requestBodyJson, headers);

        try {
            // 发送POST请求
            ResponseEntity<String> responseEntity = restTemplate.exchange(
                    "http://127.0.0.1:9000/ask",
                    HttpMethod.POST,
                    requestEntity,
                    String.class);

            // 输出响应状态码和响应体
            log.info("Response status code: " + responseEntity.getStatusCode());

            // 解析JSON响应体
            String responseBody = responseEntity.getBody();
            log.info("请求体: " + responseBody);

            // 处理空数组的情况
            String res = "";
            if (responseBody != null && !responseBody.trim().equals("[]")) {
                try {
                    JsonNode jsonNode = objectMapper.readTree(responseBody);
                    // 将JsonNode转换为字符串
                    int index = 1;
                    for (JsonNode personNode : jsonNode) {
                        res += "(" + index + ")  ";
                        // 遍历当前对象的所有字段
                        for (Iterator<String> it = personNode.fieldNames(); it.hasNext(); ) {
                            String fieldName = it.next();
                            JsonNode fieldNode = personNode.get(fieldName);

                            // 检查字段类型并输出
                            if (fieldNode.isTextual()) {
                                res += fieldName + ":" + fieldNode.asText() + "--";
                            } else if (fieldNode.isNumber()) {
                                res += fieldName + ":" + fieldNode.numberValue() + "--";
                            }
                        }
                        index++;
                    }
                    log.info("解答结果: " + res);
                    return res;
                } catch (IOException e) {
                    log.error("解析失败: " + e.getMessage());
                    return "解析响应体失败";
                }
            } else {
                // 异步执行更新操作
                CompletableFuture<Void> updateFuture = performTaskAsync();
                updateFuture.thenRun(() -> log.info("更新成功"));

                return "无查询结果，已执行更新操作。。。";
            }
        } catch (HttpClientErrorException e) {
            // 处理 400 错误
            log.error("处理 400 错误: " + e.getResponseBodyAsString());
            return "无法识别的问题类型";
        } catch (Exception e) {
            // 处理其他异常
            log.error("处理其他异常: " + e.getMessage());
            return "请求失败";
        }
    }

    @Scheduled(cron = "0 0 */6 * * *") // 每6小时执行一次
    public void performTask () {
        String url = "http://localhost:9001/sync"; // 替换为你的服务URL
        try {
            String response = restTemplate.postForObject(url, null, String.class);
            log.info("周期定时任务更新结果: " + response);
        } catch (Exception e) {
            log.error("处理错误信息: " + e.getMessage());
        }
    }
    @Async
    public CompletableFuture<Void> performTaskAsync () {
        return CompletableFuture.runAsync(() -> {
            String url = "http://localhost:9001/sync"; // 替换为你的服务URL
            try {
                String response = restTemplate.postForObject(url, null, String.class);
                log.info("异步更新结果: " + response);
            } catch (Exception e) {
                log.error("处理错误信息: " + e.getMessage());
            }
        });
    }
}
